import { PostService } from '~/server/database/services/postService'
import { requireAuth } from '~/server/utils/auth'
import type { CreatePostRequest } from '~/types/post'

export default defineEventHandler(async (event) => {
  try {
    // 验证用户身份
    const user = await requireAuth(event)

    console.log(user,'useruseruser');
    

    const body = await readBody<CreatePostRequest>(event)
    
    // 验证请求数据
    if (!body.title || !body.content) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '标题和内容不能为空' }
      })
    }

    if (body.title.length > 255) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '标题长度不能超过255个字符' }
      })
    }

    const postData = {
      title: body.title,
      content: body.content,
      authorId: user.id
    }

    const post = await PostService.createPost(postData)

    return {
      success: true,
      data: post,
      message: '帖子创建成功'
    }
  } catch (error: unknown) {
    console.error('创建帖子失败:', error)
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal Server Error',
      data: { message: '创建帖子失败' }
    })
  }
})
